import axios, { AxiosRequestConfig } from 'axios'
import { message, Modal } from 'ant-design-vue'
import { getAuthorization } from '@/utils/auth'
// 创建请求路由
const request = axios.create({
  baseURL: window.config.api,
  timeout: window.config.timeout
})

// 请求头拦截器
request.interceptors.request.use(
  (config) => {
    if (config.method === 'get' || config.method === 'GET') {
      config.url = config?.url?.indexOf('?') === -1 ? config.url + '?_=' + new Date().getTime() : config.url + '&_=' + new Date().getTime()
    }
    if (getAuthorization()) {
      config.headers[window.config.authorization] = getAuthorization() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 返回值拦截器
request.interceptors.response.use(
  (response) => {
    const status = response.status
    let data
    if (status == 200) {
      data = response.data
      const code = data.code
      if (code == 0) {
        // 正常
        return data.data
      } else if (code == -1) {
        // 已知异常
        let msg = data.msg
        message.error(msg)
        return Promise.reject('error')
      }
    }
    return data
  },
  (error) => {
    message.destroy()
    if (error.toString().indexOf('Error: Network') !== -1) {
      message.warning('网络错误,检查您的网络是否正常!')
      return Promise.reject(error)
    } else if (error.toString().indexOf('Error: timeout') !== -1) {
      message.warning('请求超时,检查您的网络是否正常!')
      return Promise.reject(error)
    } else if (error.toString().indexOf('Request failed with status code 404') !== -1) {
      let configUrl = error.config.url
      message.error({
        content: () => `请求地址404,检查您的网络地址是否正常 -> ${configUrl}`,
        style: {
          color: 'red'
        }
      })
      return Promise.reject(error)
    }
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

export default request
